package cn.fenqing168.nio.groupchat;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author fenqing
 */
public class GroupChatServer {

    /**
     * 选择器
     */
    private transient Selector selector;

    private ServerSocketChannel listenChannel;

    private static final int PORT = 7777;

    @SneakyThrows
    public GroupChatServer () {
        //初始化Selector
        selector = Selector.open();
        listenChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(PORT);
        listenChannel.bind(inetSocketAddress);
        listenChannel.configureBlocking(false);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    @SneakyThrows
    public void listenChannel(){
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()){

                SelectionKey selectionKey = selectionKeyIterator.next();
                if(selectionKey.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println(socketChannel.getRemoteAddress() + " 上线了");
                }
                if(selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    //写的方法
                }

                selectionKeyIterator.remove();
            }

        }
    }

}
